﻿using System;
using System.Collections.Generic;
using System.Threading;

namespace Study
{
    /// <summary>
    /// 多个线程主动循环取处理队列中的消息，并处理
    /// </summary>
    class Test1
    {
        static Queue<int> MsgQueue = Helper.CreateMsgQueue();

        public static void Exe()
        {
            new Thread(Work).Start("小明");
            new Thread(Work).Start("小红");
            new Thread(Work).Start("小刚");
        }

        public static void Work(object n)
        {
            Random random = new Random(DateTime.Now.Millisecond);
            string name = n.ToString() + "[" + Thread.CurrentThread.ManagedThreadId + "]";
            int exMsgCount = 0;

            bool isContinue = true;
            while (isContinue)
            {
                int msg = -1;

                lock (MsgQueue)
                {
                    if (MsgQueue.Count > 0)
                    {
                        msg = MsgQueue.Dequeue();
                        Console.WriteLine(name + " 取数据 " + msg);
                    }
                    else
                        isContinue = false;
                }

                if (msg > 0)
                {
                    int useTime = random.Next(1, 20);
                    Thread.Sleep(useTime);
                    Console.WriteLine(name + " 处理数据 " + msg + " 花费时间：" + useTime);
                    exMsgCount++;
                }
            }
            Console.WriteLine(name + " 处理数据数目 " + exMsgCount);
        }
    }
}
